/* eslint-disable no-empty */
/* eslint-disable no-unused-vars */
/* eslint-disable prettier/prettier */
// import { existsSync } from 'node:fs'
const {
  existsSync,
  mkdirSync,
  mkdtempSync,
  rmSync,
  readFileSync,
  writeFileSync,
  readdirSync,
  statSync
} = require('node:fs')
const os = require('os')
const { sep, join } = require('path')

class FsUtil {
  /**
   * 判断文件或者目录是否存在
   * @param {*} path
   * @returns
   */
  static isExist = (path) => {
    return existsSync(path)
  }

  /**
   * 创建目录
   * @param {*} dir
   * @returns 0目录存在，1创建成功，-1创建失败
   */
  static mkDir = (dir) => {
    if (!FsUtil.isExist(dir)) {
      try {
        mkdirSync(dir)
        return 1
      } catch (err) {
        console.log(err)
        return -1
      }
    }
    return 0
  }

  /**
   * 创建多层目录
   * @param {*} dir
   * @returns 0目录存在，1创建成功，-1创建失败
   */
  static mkDirs = (dir) => {
    if (!FsUtil.isExist(dir)) {
      try {
        mkdirSync(dir, { recursive: true })
        return 1
      } catch (err) {
        console.log(err)
        return -1
      }
    }
    return 0
  }

  // static mkDirss = (basePath, ...dirs) => {
  //   let pathes = ''
  //   if (dirs && dirs.length > 0) {
  //     dirs.forEach(item => {
  //       pathes = join(pathes, item)
  //     })
  //   }
  //   const pth = join(FsUtil.getHome(), pathes)
  //   console.log(pth)
  //   return FsUtil.mkDirs(pth)
  // }

  /**
   * 在系统临时路径创建临时目录
   * @returns
   */
  static mkTempDir = () => {
    let result
    // 获取系统临时目录
    const tmpDir = os.tmpdir()
    const dirPath = `${tmpDir}${sep}`
    return mkdtempSync(dirPath)
  }

  /**
   * 删除目录
   * @param {*} dirPath
   * @returns
   */
  static delDir = (dirPath) => {
    return !rmSync(dirPath, { recursive: true, force: true }) ? true : false
  }

  /**
   * 获取用户主目录
   * @returns
   */
  static getHome = () => {
    return process.env.HOME || process.env.USERPROFILE
  }

  /**
   * 读文件
   * @param {*} filePath
   * @returns
   */
  static read = (filePath) => {
    return readFileSync(filePath)
  }

  /**
   * 写文件
   * @param {*} filePath
   * @param {*} content
   */
  static write = (filePath, content) => {
    writeFileSync(filePath, content)
  }

  /**
   * 获取指定目录中的子目录
   * @param {*} dirPath
   * @returns
   */
  static getDirs = (dirPath) => {
    let result = []
    const dirs = readdirSync(dirPath)
    dirs.forEach((dir) => {
      const dirpth = join(dirPath, dir)
      try {
        const stat = statSync(dirpth)
        if (stat.isDirectory()) {
          result.push(dir)
        }
      } catch (err) {
        // console.log(err)
      }
    })
    return result
  }
}

export default FsUtil
